package org.boot.easyapi.file.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.boot.easyapi.file.config.FileStorageConfig;
import org.boot.easyapi.file.dao.FileInfoRepository;
import org.boot.easyapi.file.entity.FileInfoDO;
import org.boot.easyapi.file.service.FileUploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.UUID;

@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Resource
    private FileStorageConfig fileStorageConfig;

    @Resource
    private FileInfoRepository fileInfoRepository;

    @Override
    public FileInfoDO upload(MultipartFile file) {
        String fileKey = uuid();
        String fileType = type(file);

        Path path = Paths.get(fileStorageConfig.getRootPath() + "/" + fileKey + fileType);

        FileInfoDO fileInfo = new FileInfoDO(file.getOriginalFilename(), path.toString().replace('\\', '/'), file.getSize(), fileType, fileKey);
        try{
            Files.write(path, file.getBytes());
            fileInfo.setId(fileInfoRepository.save(fileInfo));
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new RuntimeException(e);
        }
        return fileInfo;
    }


    private String uuid() {
        return  UUID.randomUUID().toString().replaceAll("-", "");
    }

    private String type(MultipartFile file) {
        return Optional.ofNullable(file.getOriginalFilename())
                .filter(f -> f.contains("."))
                .map(f -> f.substring(f.lastIndexOf(".")).toLowerCase())
                .orElse("");
    }
}
